/*
 * Copyright (c) 2009 Frederic Daoud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.stripesbook.rayures.view;

import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

/**
 * A tag has a name an optional set of attributes, and may have child objects. Its associated
 * template renders the tag in HTML:
 * 
 * <pre>
 * &lt;$tagName$!attributes&gt;#foreach ($child in $children)$child#end&lt;/$tagName&gt;
 * </pre>
 *
 * @author Frederic Daoud
 */
public class ViewTag<V extends ViewTag<?>> extends ViewTemplate<V> {

  private Map<String, String> attributes = new TreeMap<String, String>();

  /**
   * Constructs an HTML tag with the given tag name.
   */
  public V tagName(String tagName) {
    put("tagName", tagName);
    return getThis();
  }

  /**
   * Returns the set of attributes, if any have been added to the tag. If not, an empty map is
   * returned.
   */
  public Map<String, String> getAttributes() {
    return attributes;
  }

  /**
   * Adds an attribute to the tag, returning the tag object itself, making it possible to use method
   * chaining.
   */
  public V attr(String name, String value) {
    attributes.put(name, value);
    writeAttributesToObjectMap();
    return getThis();
  }

  /**
   * Convenience method for adding several child objects.
   */
  @Override
  public V add(Object... childObjects) {
    V result = super.add(childObjects);
    put("children", getChildren());
    return result;
  }

  /**
   * Constructs the string to be output in the template for the attributes, in the form
   * {@code key1="value1" key2="value2"}.
   */
  protected void writeAttributesToObjectMap() {
    StringBuilder builder = new StringBuilder();

    for (Entry<String, String> entry : getAttributes().entrySet()) {
      builder.append(" ");
      String name = entry.getKey();
      String value = entry.getValue();
      builder.append(name).append("=\"").append(value).append('"');
    }
    put("attributes", builder.toString());
  }
}
